﻿using AForge.Controls;
using AForge.Video;
using AForge.Video.DirectShow;
using AForge.Imaging.Filters;
using Baidu.Aip.Face;
using BaiduAI.Common;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Interop;
using System.Windows.Media.Imaging;

namespace BaiduAI
{
    public partial class Form1 : Form
    {
        private string APP_ID = "33711276";
        private string API_KEY = "4biNOux3xUduwddgrV6fUybL";
        private string SECRET_KEY = "0iDdSEiuSZ0ys4GqGQxwwvelGwKfhRgq";

        private Face client = null;
        private bool IsStart = false;
        private FaceLocation location = null;

        private FilterInfoCollection videoDevices = null;
        private VideoCaptureDevice videoSource;

        public Form1()
        {
            InitializeComponent();
            axWindowsMediaPlayer1.uiMode = "Invisible";
            client = new Face(API_KEY, SECRET_KEY);
        }

        public string ConvertImageToBase64(Image file)
        {
            if (file == null)
            {
                throw new ArgumentNullException(nameof(file), "传入的Image对象不能为null");
            }
            using (MemoryStream memoryStream = new MemoryStream())
            {
                file.Save(memoryStream, file.RawFormat);
                byte[] imageBytes = memoryStream.ToArray();
                return Convert.ToBase64String(imageBytes);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.InitialDirectory = "D:\\new\\BaiduAI\\bin\\Debug";
            dialog.Filter = "所有文件|*.*";
            dialog.RestoreDirectory = true;
            dialog.FilterIndex = 1;
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                string filename = dialog.FileName;
                try
                {
                    Image im = Image.FromFile(filename);
                    if (im == null)
                    {
                        MessageBox.Show("加载图像失败，图像为null");
                        return;
                    }
                    var image = ConvertImageToBase64(im);
                    string imageType = "BASE64";

                    var options = new Dictionary<string, object>{
                        {"face_field", "age,beauty"},
                        {"face_fields", "age,qualities,beauty"}
                    };

                    var options1 = new Dictionary<string, object>{
                        {"face_field", "age"},
                        {"max_face_num", 2},
                        {"face_type", "LIVE"},
                        {"liveness_control", "LOW"}
                    };

                    var result = client.Detect(image, imageType, options);
                    textBox1.Text = result.ToString();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        public string ReadImg(string img)
        {
            return Convert.ToBase64String(File.ReadAllBytes(img));
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBox2.Text) || string.IsNullOrEmpty(textBox3.Text))
            {
                MessageBox.Show("请选择要对比的人脸图片");
                return;
            }
            try
            {
                string path1 = textBox2.Text;
                string path2 = textBox3.Text;

                var faces = new JArray
                {
                    new JObject
                    {
                        {"image", ReadImg(path1)},
                        {"image_type", "BASE64"},
                        {"face_type", "LIVE"},
                        {"quality_control", "LOW"},
                        {"liveness_control", "NONE"},
                    },
                    new JObject
                    {
                        {"image", ReadImg(path2)},
                        {"image_type", "BASE64"},
                        {"face_type", "LIVE"},
                        {"quality_control", "LOW"},
                        {"liveness_control", "NONE"},
                    }
                };

                var result = client.Match(faces);
                textBox1.Text = result.ToString();
            }
            catch (Exception ex)
            { }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.InitialDirectory = "D:\\";
            dialog.Filter = "所有文件|*.*";
            dialog.RestoreDirectory = true;
            dialog.FilterIndex = 2;
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                if (string.IsNullOrEmpty(textBox2.Text))
                {
                    textBox2.Text = dialog.FileName;
                }
                else
                {
                    textBox3.Text = dialog.FileName;
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            if (videoDevices != null && videoDevices.Count > 0)
            {
                foreach (FilterInfo device in videoDevices)
                {
                    comboBox1.Items.Add(device.Name);
                }
                comboBox1.SelectedIndex = 0;
            }

            // 初始化复选框状态（默认选择正常模式）
            checkBox1.Checked = true;
            checkBox2.Checked = false;

            videoSourcePlayer1.NewFrame += VideoSourcePlayer1_NewFrame;

            ThreadPool.QueueUserWorkItem(new WaitCallback(p => {
                while (true)
                {
                    IsStart = true;
                    Thread.Sleep(1000);
                }
            }));
        }

        private void VideoSourcePlayer1_NewFrame(object sender, ref Bitmap image)
        {
            if (image == null)
            {
                ClassLoger.Error("VideoSourcePlayer1_NewFrame", new Exception("采集到的图像帧为null"));
                return;
            }
            try
            {
                if (IsStart)
                {
                    IsStart = false;
                    ThreadPool.QueueUserWorkItem(new WaitCallback(this.Detect), image.Clone());
                }
                if (location != null)
                {
                    try
                    {
                        Graphics g = Graphics.FromImage(image);
                        g.DrawLine(new Pen(Color.Black), new System.Drawing.Point(location.left, location.top), new System.Drawing.Point(location.left + location.width, location.top));
                        g.DrawLine(new Pen(Color.Black), new System.Drawing.Point(location.left, location.top), new System.Drawing.Point(location.left, location.top + location.height));
                        g.DrawLine(new Pen(Color.Black), new System.Drawing.Point(location.left, location.top + location.height), new System.Drawing.Point(location.left + location.width, location.top + location.height));
                        g.DrawLine(new Pen(Color.Black), new System.Drawing.Point(location.left + location.width, location.top), new System.Drawing.Point(location.left + location.width, location.top + location.height));
                        g.Dispose();
                    }
                    catch (Exception ex)
                    {
                        ClassLoger.Error("VideoSourcePlayer1_NewFrame", ex);
                    }
                }
            }
            catch (Exception ex)
            {
                ClassLoger.Error("VideoSourcePlayer1_NewFrame1", ex);
            }
        }

        private void CameraConn()
        {
            if (comboBox1.Items.Count <= 0)
            {
                MessageBox.Show("请插入视频设备");
                return;
            }
            videoSource = new VideoCaptureDevice(videoDevices[comboBox1.SelectedIndex].MonikerString);
            videoSource.DesiredFrameSize = new System.Drawing.Size(320, 240);
            videoSource.DesiredFrameRate = 1;

            videoSourcePlayer1.VideoSource = videoSource;
            videoSourcePlayer1.Start();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            if (videoDevices != null && videoDevices.Count > 0)
            {
                foreach (FilterInfo device in videoDevices)
                {
                    comboBox1.Items.Add(device.Name);
                }
                comboBox1.SelectedIndex = 0;
            }
        }

        /// <summary>
        /// 拍照功能（支持正常/美颜模式）
        /// </summary>
        private void button5_Click(object sender, EventArgs e)
        {
            if (comboBox1.Items.Count <= 0)
            {
                MessageBox.Show("请插入视频设备");
                return;
            }
            try
            {
                if (videoSourcePlayer1.IsRunning)
                {
                    Bitmap originalFrame = videoSourcePlayer1.GetCurrentVideoFrame();
                    if (originalFrame == null)
                    {
                        MessageBox.Show("无法获取当前视频帧");
                        return;
                    }

                    Bitmap processedFrame;
                    string modeSuffix = "";

                    try
                    {
                        // 根据复选框选择决定是否应用美颜
                        if (checkBox2.Checked) // 假设checkBox2为"美颜"选项
                        {
                            processedFrame = ApplyBeautyFilter(originalFrame);
                            modeSuffix = "_beauty";
                        }
                        else // checkBox1为"正常"选项
                        {
                            processedFrame = new Bitmap(originalFrame); // 正常模式，不处理
                            modeSuffix = "";
                        }

                        // 转换并保存图片
                        BitmapSource bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(
                            processedFrame.GetHbitmap(),
                            IntPtr.Zero,
                            Int32Rect.Empty,
                            BitmapSizeOptions.FromEmptyOptions());

                        PngBitmapEncoder encoder = new PngBitmapEncoder();
                        encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
                        string picName = GetImagePath() + "\\" + DateTime.Now.ToFileTime() + modeSuffix + ".jpg";

                        if (File.Exists(picName))
                        {
                            File.Delete(picName);
                        }
                        using (Stream stream = File.Create(picName))
                        {
                            encoder.Save(stream);
                        }

                        MessageBox.Show($"照片已保存至: {picName}");

                        // 关闭摄像头并退出
                        if (videoSourcePlayer1 != null && videoSourcePlayer1.IsRunning)
                        {
                            videoSourcePlayer1.SignalToStop();
                            videoSourcePlayer1.WaitForStop();
                        }
                        this.Close();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"拍照处理出错: {ex.Message}，将保存原始照片");
                        // 出错时保存原始照片
                        BitmapSource bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(
                            originalFrame.GetHbitmap(),
                            IntPtr.Zero,
                            Int32Rect.Empty,
                            BitmapSizeOptions.FromEmptyOptions());

                        PngBitmapEncoder encoder = new PngBitmapEncoder();
                        encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
                        string picName = GetImagePath() + "\\" + DateTime.Now.ToFileTime() + "_error.jpg";

                        if (File.Exists(picName))
                        {
                            File.Delete(picName);
                        }
                        using (Stream stream = File.Create(picName))
                        {
                            encoder.Save(stream);
                        }
                    }
                    finally
                    {
                        originalFrame.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("摄像头异常：" + ex.Message);
            }
        }

        private string GetImagePath()
        {
            string personImgPath = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory)
                         + Path.DirectorySeparatorChar.ToString() + "PersonImg";
            if (!Directory.Exists(personImgPath))
            {
                Directory.CreateDirectory(personImgPath);
            }
            return personImgPath;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            CameraConn();
        }

        public byte[] Bitmap2Byte(Bitmap bitmap)
        {
            if (bitmap == null)
            {
                ClassLoger.Error("Bitmap2Byte", new ArgumentNullException(nameof(bitmap)));
                return null;
            }
            try
            {
                using (MemoryStream stream = new MemoryStream())
                {
                    bitmap.Save(stream, ImageFormat.Jpeg);
                    byte[] data = new byte[stream.Length];
                    stream.Seek(0, SeekOrigin.Begin);
                    stream.Read(data, 0, Convert.ToInt32(stream.Length));
                    return data;
                }
            }
            catch (Exception ex)
            {
                ClassLoger.Error("Bitmap2Byte", ex);
            }
            return null;
        }

        public byte[] BitmapSource2Byte(BitmapSource source)
        {
            if (source == null)
            {
                ClassLoger.Error("BitmapSource2Byte", new ArgumentNullException(nameof(source)));
                return null;
            }
            try
            {
                JpegBitmapEncoder encoder = new JpegBitmapEncoder();
                encoder.QualityLevel = 100;
                using (MemoryStream stream = new MemoryStream())
                {
                    encoder.Frames.Add(BitmapFrame.Create(source));
                    encoder.Save(stream);
                    byte[] bit = stream.ToArray();
                    stream.Close();
                    return bit;
                }
            }
            catch (Exception ex)
            {
                ClassLoger.Error("BitmapSource2Byte", ex);
            }
            return null;
        }

        public void Detect(object image)
        {
            if (image == null || !(image is Bitmap))
            {
                ClassLoger.Error("Detect", new Exception("传入的image参数为null或类型不是Bitmap"));
                return;
            }
            if (image != null && image is Bitmap)
            {
                try
                {
                    Bitmap img = (Bitmap)image;
                    var imgByte = Bitmap2Byte(img);
                    Image im = img;
                    string image1 = ConvertImageToBase64(im);
                    string imageType = "BASE64";

                    if (imgByte != null)
                    {
                        var options = new Dictionary<string, object>{
                            {"max_face_num", 2},
                            {"face_fields", "age,qualities,beauty"}
                        };
                        var result = client.Detect(image1, imageType, options);
                        FaceDetectInfo detect = JsonHelper.DeserializeObject<FaceDetectInfo>(result.ToString());
                        if (detect != null && detect.result_num > 0)
                        {
                            ageText.Text = detect.result[0].age.TryToString();
                            this.location = detect.result[0].location;
                            StringBuilder sb = new StringBuilder();
                            if (detect.result[0].qualities != null)
                            {
                                if (detect.result[0].qualities.blur >= 0.7) sb.AppendLine("人脸过于模糊");
                                if (detect.result[0].qualities.completeness >= 0.4) sb.AppendLine("人脸不完整");
                                if (detect.result[0].qualities.illumination <= 40) sb.AppendLine("灯光光线质量不好");
                                if (detect.result[0].qualities.occlusion != null)
                                {
                                    if (detect.result[0].qualities.occlusion.left_cheek >= 0.8) sb.AppendLine("左脸颊不清晰");
                                    if (detect.result[0].qualities.occlusion.left_eye >= 0.6) sb.AppendLine("左眼不清晰");
                                    if (detect.result[0].qualities.occlusion.mouth >= 0.7) sb.AppendLine("嘴巴不清晰");
                                    if (detect.result[0].qualities.occlusion.nose >= 0.7) sb.AppendLine("鼻子不清晰");
                                    if (detect.result[0].qualities.occlusion.right_cheek >= 0.8) sb.AppendLine("右脸颊不清晰");
                                    if (detect.result[0].qualities.occlusion.right_eye >= 0.6) sb.AppendLine("右眼不清晰");
                                    if (detect.result[0].qualities.occlusion.chin >= 0.6) sb.AppendLine("下巴不清晰");
                                }
                                if (detect.result[0].pitch >= 20) sb.AppendLine("俯视角度太大");
                                if (detect.result[0].roll >= 20) sb.AppendLine("脸部应该放正");
                                if (detect.result[0].yaw >= 20) sb.AppendLine("脸部应该放正点");
                            }
                            if (detect.result[0].location.height <= 100 || detect.result[0].location.width <= 100)
                            {
                                sb.AppendLine("人脸部分过小");
                            }
                            textBox4.Text = sb.ToString();
                            if (textBox4.Text.IsNull()) textBox4.Text = "OK";
                        }
                    }
                }
                catch (Exception ex)
                {
                    ClassLoger.Error("Form1.image", ex);
                }
            }
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            System.Environment.Exit(0);
        }

        private void button7_Click(object sender, EventArgs e)
        {
            string uid = "dd";
            string userInfo = textBox6.Text.Trim();
            string groupId = textBox5.Text.Trim();

            if (comboBox1.Items.Count <= 0)
            {
                MessageBox.Show("请插入视频设备");
                return;
            }
            try
            {
                if (videoSourcePlayer1.IsRunning)
                {
                    BitmapSource bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(
                                    videoSourcePlayer1.GetCurrentVideoFrame().GetHbitmap(),
                                    IntPtr.Zero,
                                    Int32Rect.Empty,
                                    BitmapSizeOptions.FromEmptyOptions());
                    var img = BitmapSource2Byte(bitmapSource);
                    var options = new Dictionary<string, object>{
                        {"action_type", "replace"}
                    };
                    var result = "";
                    if (result.ToString().Contains("error_code"))
                    {
                        MessageBox.Show("注册失败:" + result.ToString());
                    }
                    else
                    {
                        MessageBox.Show("注册成功");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("摄像头异常：" + ex.Message);
            }
        }

        private void button8_Click(object sender, EventArgs e)
        {
            string uid = "dd";
            string userInfo = textBox6.Text.Trim();
            string groupId = textBox5.Text.Trim();

            if (comboBox1.Items.Count <= 0)
            {
                MessageBox.Show("请插入视频设备");
                return;
            }
            try
            {
                if (videoSourcePlayer1.IsRunning)
                {
                    BitmapSource bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(
                                    videoSourcePlayer1.GetCurrentVideoFrame().GetHbitmap(),
                                    IntPtr.Zero,
                                    Int32Rect.Empty,
                                    BitmapSizeOptions.FromEmptyOptions());

                    var img = BitmapSource2Byte(bitmapSource);
                    if (img == null)
                    {
                        MessageBox.Show("图像转换字节数组失败，无法进行人脸登录");
                        return;
                    }
                    var options = new Dictionary<string, object>{
                        {"match_threshold", 70},
                        {"quality_control", "NORMAL"},
                        {"liveness_control", "LOW"},
                        {"max_user_num", 3}
                    };

                    var image = Convert.ToBase64String(img);
                    var imageType = "BASE64";
                    var groupIdList = "11";

                    var result = client.Search(image, imageType, groupIdList, options);

                    if (result.Value<int>("error_code") == 0)
                    {
                        JArray array = result["result"].Value<JArray>("user_list");
                        textBox7.Text = array[0].Value<string>("user_id");
                        axWindowsMediaPlayer1.URL = "20230522_160638_1.mp3";
                        axWindowsMediaPlayer1.Ctlcontrols.play();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("摄像头异常：" + ex.Message);
            }
        }

        private void button9_Click(object sender, EventArgs e)
        {
            axWindowsMediaPlayer1.Ctlcontrols.stop();
            if (videoDevices == null || videoDevices.Count == 0)
            {
                return;
            }
            videoSource.Stop();
            videoSourcePlayer1.Stop();
        }

        /// <summary>
        /// 应用增强版美颜滤镜（效果更夸张）
        /// </summary>
        private Bitmap ApplyBeautyFilter(Bitmap source)
        {
            try
            {
                // 创建副本避免修改原图
                Bitmap result = new Bitmap(source.Width, source.Height);

                // 1. 强力磨皮（增强高斯模糊效果）
                GaussianBlur blurFilter = new GaussianBlur(5); // 增大模糊半径，效果更明显
                Bitmap blurred = blurFilter.Apply(source);

                // 2. 美白处理（增强亮度和对比度）
                BrightnessCorrection brightnessFilter = new BrightnessCorrection(25); // 增加亮度
                Bitmap brightened = brightnessFilter.Apply(blurred);

                ContrastCorrection contrastFilter = new ContrastCorrection(20); // 增加对比度
                Bitmap contrasted = contrastFilter.Apply(brightened);

                // 3. 强力瘦脸（增大变形幅度）
                RectangleDeformation deformationFilter = new RectangleDeformation(
                    new Rectangle(source.Width / 4, source.Height / 3, source.Width / 2, source.Height / 3),
                    -20); // 增大压缩比例，瘦脸效果更明显
                Bitmap deformed = deformationFilter.Apply(contrasted);

                // 4. 大眼效果（对眼睛区域进行放大）
                // 假设眼睛位置在人脸区域上方1/3处
                EllipseDeformation eyeDeformation = new EllipseDeformation(
                    new Rectangle(source.Width / 3, source.Height / 3, source.Width / 3, source.Height / 6),
                    15); // 正数表示放大
                Bitmap bigEyes = eyeDeformation.Apply(deformed);

                // 5. 腮红效果（在脸颊区域添加红色调）
                Bitmap withBlush = AddBlushEffect(bigEyes);

                // 6. 锐化处理（增强细节，让夸张效果更明显）
                Sharpen sharpenFilter = new Sharpen();
                Bitmap sharpened = sharpenFilter.Apply(withBlush);

                // 7. 最终结果
                using (Graphics g = Graphics.FromImage(result))
                {
                    g.DrawImage(sharpened, 0, 0);
                }

                return result;
            }
            catch (Exception ex)
            {
                ClassLoger.Error("ApplyBeautyFilter", ex);
                return new Bitmap(source); // 出错时返回原图
            }
        }

        /// <summary>
        /// 添加腮红效果
        /// </summary>
        private Bitmap AddBlushEffect(Bitmap source)
        {
            try
            {
                Bitmap result = new Bitmap(source);
                Graphics g = Graphics.FromImage(result);

                // 创建半透明红色画刷（腮红颜色）
                Brush blushBrush = new SolidBrush(Color.FromArgb(100, 255, 180, 180));

                // 在脸颊位置绘制椭圆（位置和大小可根据需要调整）
                int faceWidth = source.Width / 2;
                int faceHeight = source.Height / 3;
                int leftCheekX = source.Width / 4 - faceWidth / 6;
                int rightCheekX = source.Width * 3 / 4 - faceWidth / 6;
                int cheekY = source.Height / 3;

                // 左侧腮红
                g.FillEllipse(blushBrush, leftCheekX, cheekY, faceWidth / 3, faceHeight / 3);

                // 右侧腮红
                g.FillEllipse(blushBrush, rightCheekX, cheekY, faceWidth / 3, faceHeight / 3);

                g.Dispose();
                return result;
            }
            catch (Exception ex)
            {
                ClassLoger.Error("AddBlushEffect", ex);
                return source;
            }
        }
    }
}